import { Injectable } from '@angular/core';

export interface ElectronAPI {
  invoke: (channel: string, data?: any) => Promise<any>;
  send: (channel: string, data?: any) => void;
  onReceive: (channel: string, callback: Function) => void;
}

@Injectable({
  providedIn: 'root'
})
export class ElectronService {
  private electronAPI: ElectronAPI | null = null;

  constructor() {
    if (this.isElectron()) {
      this.electronAPI = (window as any).electronAPI;
    }
  }

  isElectron(): boolean {
    return !!(window && (window as any).electronAPI);
  }

  // 渲染器向主进程的双向调用，需使用await等待返回值
  invoke(channel: string, data?: any): Promise<any> {
    return this.electronAPI?.invoke(channel, data)!;
  }

  // 渲染器向主进程的单项调用，无返回值
  send(channel: string, data?: any): void {
    this.electronAPI?.send(channel, data);
  }

  // 在渲染器上注册事件，监听来自主进程的消息
  onReceive(channel: string, callback: Function): void {
    this.electronAPI?.onReceive(channel, callback);
  }

}
